<?php

class yanzPage {

    private $width;
    private $height;
    private $num;
    private $yanz; //验证码保证不重复
    private $img;

    function __construct($width, $height, $num) {
        $this->width = $width;
        $this->height = $height;
        $this->num = $num;
        $this->yanz = $this->getyanz();
    }

    private function getyanz() {
        $yanz = '3456789abcdefghijkmnpqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXY';
        $yanzm = '';
        for ($i = 0; $i < $this->num; $i++) {
            $yanzm .=$yanz{rand(0, strlen($yanz) - 1)}; //从0开始随机
        }
        return $yanzm;
    }

    function getfont() {
        return $this->yanz; //得到字符的验证码存到服务器;
    }

    //输出到页面上 需要这一步进行调用
    function echotuxiang() {
        $this->background(); //创建背景
        $this->huafont(); //输出画字
        $this->ganrao();  //干扰
        $this->printimg(); //输出图像
    }

    private function background() {
        $this->img = imagecreatetruecolor($this->width, $this->height); //创建背景
        $bgcolor = imagecolorallocate($this->img, rand(225, 255), rand(225, 255), rand(225, 255)); //取随机颜色
        imagefill($this->img, 0, 0, $bgcolor); //填颜色
        $bordercolor = imagecolorallocate($this->img, 0, 0, 0); //画边框
        imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1, $bordercolor); //画一个矩形 会出去一个像素所以-1
    }

    private function huafont() {
        for ($i = 0; $i < $this->num; $i++) {
            $color = imagecolorallocate($this->img, rand(0, 120), rand(0, 120), rand(0, 120));
            $fontsize = rand(14, 15); //随机字体大小
            $x = 5 + ($this->width / $this->num) * $i; //水平位置
            $y = rand(0, imagefontheight($fontsize));  //随机高度
            imagechar($this->img, $fontsize, $x, $y, $this->yanz{$i}, $color); //画每个字符 ，imagestring画所有字符
            //(背景,字体,从0到0开始，画什么字符,颜色)
        }
    }

    private function ganrao() {
        for ($i = 0; $i < 100; $i++) { //100个点 ,然后每个点需要一个不一样的颜色
            $color = imagecolorallocate($this->img, rand(0, 255), rand(0, 255), rand(0, 255));
            imagesetpixel($this->img, rand(1, $this->width-2), rand(1, $this->height-2), $color);
        }
    }

    private function printimg() {
        if (imagetypes() & IMG_GIF) {
            header("Content-type: image/gif");
            imagegif($this->img);
        } elseif (imagetypes() & IMG_JPEG) {
            header("Content-type: image/jpeg");
            imagejpeg($this->img);
        } elseif (imagetypes() & IMG_PNG) {
            header("Content-type: image/png");
            imagepng($this->img);
        } else {
            die("No image support in this PHP server");
        }
    }

    function __destruct() {
        imagedestroy($this->img); //销毁图像
    }

}
